/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.droidcon.apps.template.io.json;

import org.droidcon.apps.template.io.XmlHandler.HandlerException;
import org.droidcon.apps.template.util.ParserUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import com.google.gson.stream.JsonReader;

import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Opens a local {@link Resources#getXml(int)} and passes the resulting
 * {@link XmlPullParser} to the given {@link XmlHandler}.
 */
public class LocalJsonExecutor {
	private Resources mRes;
	private ContentResolver mResolver;

	public LocalJsonExecutor(Resources res, ContentResolver resolver) {
		mRes = res;
		mResolver = resolver;
	}

	public void execute(Context context, String assetName, JsonHandler handler)
			throws HandlerException {
		try {
			final InputStream input = context.getAssets().open(assetName);
			JsonReader reader = new JsonReader(new InputStreamReader(input,
					"UTF-8"));
			handler.parseAndApply(reader, mResolver);
			reader.close();
		} catch (HandlerException e) {
			throw e;
		} catch (IOException e) {
			throw new HandlerException("Problem parsing local asset: "
					+ assetName, e);
		}
	}

	public void execute(int resId, JsonHandler handler) throws HandlerException {
		try {
			final InputStream input = mRes.openRawResource(resId);
			JsonReader reader = new JsonReader(new InputStreamReader(input,
					"UTF-8"));
			handler.parseAndApply(reader, mResolver);
			reader.close();
		} catch (HandlerException e) {
			throw e;
		} catch (IOException e) {
			throw new HandlerException("Problem parsing local asset: "
					+ resId, e);
		}
	}
}
